<template>
<div>
  <!--    面包屑导航-->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    <el-breadcrumb-item>角色列表</el-breadcrumb-item>
  </el-breadcrumb>
  <el-card :style="{height:height}">
    <el-row>
      <el-col>
        <el-button type="primary" @click="showAddUserInfoDialog">添加角色</el-button>
      </el-col>
    </el-row>
    <el-table :data="rolesList" border stripe>
<!--      展开列-->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row :class="['bdbottom',i1==0?'':'bdtop','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
<!--            渲染一级权限-->
            <el-col :span="5">
              <el-tag closable @close="removeById(scope.row,item1.id)">{{item1.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
<!--            二级和三级权限-->
            <el-col :span="19">
              <el-row :class="[i2==0?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                <el-col :span="6">
                  <el-tag type="success" closable @close="removeById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18" >
                  <el-tag type="warning" v-for="(item3,i3) in item2.children" :key="item3.id" closable @close="removeById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <pre></pre>
        </template>
      </el-table-column>
      <el-table-column type="index"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作" width="300px">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditUserInfoDialogVisiable(scope.row.id)">编辑</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleUserInfo(scope.row.id)">删除</el-button>
          <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
<!--  分配权限-->
  <el-dialog
    title="提示"
    :visible.sync="setRightDialogVisiable"
    width="50%"
    @close="setRightDialogClosed"
  >
    <el-tree :data="rightsList" :props="treeProps"  show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
    <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialogVisiable = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
  </el-dialog>
  <!--  添加角色-->
  <el-dialog
    title="提示"
    :visible.sync="addUserInfoDialogVisiable"
    width="50%"
    @close="addUserInfoDialogClosed"
  >
    <el-form :model="addForm" :rules="addFormUserInfo" ref="addFormRef" label-width="100px">
      <el-form-item label="角色名" prop="roleName">
        <el-input v-model="addForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="addForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="addUserInfoDialogVisiable = false">取 消</el-button>
    <el-button type="primary" @click="addUserInfo">确 定</el-button>
  </span>
  </el-dialog>
  <!--  修改角色-->
  <el-dialog
    title="提示"
    :visible.sync="editUserInfoDialogVisiable"
    width="50%"
    @close="editUserInfoDialogClosed"
  >
    <el-form :model="editForm" :rules="editFormUserInfo" ref="editFormRef" label-width="100px">
      <el-form-item label="角色名" prop="roleName">
        <el-input v-model="editForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="editForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="editUserInfoDialogVisiable = false">取 消</el-button>
    <el-button type="primary" @click="editUserInfo">确 定</el-button>
  </span>
  </el-dialog>
</div>
</template>

<script>
export default {
  name: "roles",
  data(){
    return{
      rolesList:[],
      setRightDialogVisiable:false,//权限对话框的显示
      addUserInfoDialogVisiable:false,//添加角色
      editUserInfoDialogVisiable:false,//修改角色
      rightsList:[],
      treeProps:{
        label:'authName',
        children:'children'
      },
      defKeys:[],
      height:0,
      roleId:'',
      addForm:{
        roleName:'',
        roleDesc:'',
      },
      addFormUserInfo:{
        roleName:[
          {required:true,message:'角色名不能为空',trigger:'blur'},
        ],
      },
      editForm:{},
      editFormUserInfo:{
        roleName:[
          {required:true,message:'角色名不能为空',trigger:'blur'},
        ],
      },
    }
  },
  methods:{
    //获取角色列表
   async getRolesList(){
      const {data:res} = await this.$shop.get('roles');
      if(res.meta.status !==200){
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data;
    },
    //根据id删除用户
    removeById(row,rightId){
      this.$confirm('此操作将删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$shop.delete(`roles/${row.id}/rights/${rightId}}`)
          .then(res=>{
            debugger
          if(res.data.meta.status !== 200){
            return this.$message.error('删除权限失败')
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          row.children = res.data.data
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 权限对话框
    async showSetRightDialog(row){
     this.roleId = row.id;
     const {data:res} = await this.$shop.get('rights/tree');
      if(res.meta.status !==200){
        return this.$message.error('获取权限数据失败')
      }
      //递归获取三级节点
      this.getLiefKeys(row,this.defKeys)
      this.rightsList = res.data;
     this.setRightDialogVisiable = true;
    },
    //获取角色下的权限ID
    getLiefKeys(node,arr){
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach((item)=>{
        this.getLiefKeys(item,arr)
      })
    },
    setRightDialogClosed(){
      this.defKeys = [];
    },
    allotRights(){
     const keys = [
       ...this.$refs.treeRef.getCheckedKeys(),
       ...this.$refs.treeRef.getHalfCheckedKeys()
     ];
     const idStr = keys.join(',');
     this.$shop.post(`roles/${this.roleId}/rights/`,{rids:idStr}).then(res=>{
       if(res.data.meta.status !==200){
         return this.$message.error('分配权限失败')
       }
       this.$message.success('分配权限成功')
       this.getRolesList();
       this.setRightDialogVisiable = false;
     })
    },
    //显示添加角色
    showAddUserInfoDialog(){
      this.addUserInfoDialogVisiable = true;
    },
    //添加角色
    addUserInfo(){
      this.$refs.addFormRef.validate(valid=>{
        if(!valid) return;
        this.$shop.post('roles',this.addForm).then(res=>{
          if(res.data.meta.status !==201){
            this.$message.error('添加失败')
          }
          this.$message.success('添加成功');
          this.addUserInfoDialogVisiable = false;
          this.getRolesList();
        })
      })
    },
    //监听添加角色关闭
    addUserInfoDialogClosed(){
      this.$refs.addFormRef.resetFields();
    },
    //显示修改角色
    async showEditUserInfoDialogVisiable(id){
      this.editUserInfoDialogVisiable = true;
      const {data:res} = await this.$shop.get('roles/'+id)
      if(res.meta.status !== 200){
        return this.$message.error('查询失败')
      }
      this.editForm = res.data
    },
    // 保存修改角色
    editUserInfo(){
      this.$refs.editFormRef.validate(valid=>{
        if(!valid) return;
        this.$shop.put('roles/'+this.editForm.roleId,{roleName:this.editForm.roleName,roleDesc:this.editForm.roleDesc}).then(res=>{
          if(res.data.meta.status !==200){
            return this.$message.error('修改角色失败')
          }
          this.editUserInfoDialogVisiable = false;
          this.getRolesList();
          this.$message.success('更新用户数据成功')
        })
      })
    },
    editUserInfoDialogClosed(){
      this.$refs.editFormRef.resetFields();
    },
    //删除
    deleUserInfo(id){
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$shop.delete('roles/'+id).then(res=>{
          if(res.data.meta.status !==200){
            return this.$message.error('删除失败')
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getRolesList()
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
  },
  created() {
    this.getRolesList();
    // 获取屏幕高度
    this.height = document.documentElement.clientHeight-115+'px';
  },
}
</script>

<style scoped>
  .el-tag{
    margin: 7px;
  }
  .bdtop{
    border-top: 1px solid #eeeeee;
  }
  .bdbottom{
    border-bottom: 1px solid #eee;
  }
  .vcenter{
    display: flex;
    align-items: center;
  }
</style>
